package com.bigmi.admin.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigmi.admin.mapper.AdNewsMapper;
import com.bigmi.admin.mapper.WmChannelMapper;
import com.bigmi.admin.mapper.WmUserMapper;
import com.bigmi.admin.service.AdNewsService;
import com.bigmi.apis.article.ArticleClientIp;
import com.bigmi.model.admin.dto.NewsAuthDto;
import com.bigmi.model.admin.dto.NewsNameDto;
import com.bigmi.model.article.Dto.ArticleDto;
import com.bigmi.model.common.dtos.PageResponseResult;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.common.enums.AppHttpCodeEnum;
import com.bigmi.model.wemedia.pojos.WmChannel;
import com.bigmi.model.wemedia.pojos.WmNews;
import com.bigmi.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class AdNewsServiceImpl extends ServiceImpl<AdNewsMapper, WmNews> implements AdNewsService {
    @Autowired
    private AdNewsMapper adNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    //feign接口调用
    @Autowired
    private ArticleClientIp articleClientIp;

    @Override
    public ResponseResult listOv(NewsAuthDto newsAuthDto) {
        if (newsAuthDto ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //分页查询
        IPage page =new Page(newsAuthDto.getPage(),newsAuthDto.getSize());
        Page<NewsNameDto> p = new Page();
        LambdaQueryWrapper<WmNews> queryWrapper =new LambdaQueryWrapper<>();
        //模糊查询
        if (StringUtils.isNotBlank(newsAuthDto.getTitle())){
            queryWrapper.like(WmNews::getTitle,newsAuthDto.getTitle());
        }
        //条件查询全部
        if (newsAuthDto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,newsAuthDto.getStatus());
        }
        queryWrapper.orderByDesc(WmNews::getSubmitedTime);
        //查询作者
        page =page(page,queryWrapper);
        BeanUtils.copyProperties(page,p,"records");
        List<WmNews> pageRecords = page.getRecords();
        List<NewsNameDto> newsNameDtoList = pageRecords.stream().map((item) ->{
            NewsNameDto newsNameDto = new NewsNameDto();
            BeanUtils.copyProperties(item,newsNameDto,"userId");
            WmUser wmUser = wmUserMapper.selectById(item.getUserId());
            newsNameDto.setAuthorName(wmUser.getName());
            return newsNameDto;
        }).collect(Collectors.toList());
        PageResponseResult responseResult = new PageResponseResult(newsAuthDto.getPage(), newsAuthDto.getSize(), (int) page.getTotal());
        responseResult.setData(newsNameDtoList);
       // responseResult.setData(page.getRecords());
        List records = page.getRecords();
        log.info(""+records);
        log.info(""+responseResult);
        return responseResult;
    }

    @Override
    public ResponseResult oneOv(Integer id) {
        WmNews wmNews = adNewsMapper.selectById(id);
        NewsNameDto newsNameDto = new NewsNameDto();
        BeanUtils.copyProperties(wmNews,newsNameDto,"userId");
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        newsNameDto.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(newsNameDto);
    }
    //审核失败
    @Override
    public ResponseResult authFail(NewsAuthDto newsAuthDto) {
        if (newsAuthDto ==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        System.out.println(newsAuthDto);
        WmNews wmNews =new WmNews();
        wmNews.setId(newsAuthDto.getId());
        wmNews.setStatus(newsAuthDto.getStatus());
        wmNews.setReason(newsAuthDto.getMsg());
        adNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    //审核成功
    @Override
    public ResponseResult authPass(NewsAuthDto newsAuthDto) {

        if (newsAuthDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer id = newsAuthDto.getId();
        System.out.println(id+"?/////////////////");
        WmNews wmNews = adNewsMapper.selectById(id);
        if (wmNews==null){
            throw new RuntimeException("文章不存在");
        }
        wmNews.setId(newsAuthDto.getId());
        wmNews.setStatus(newsAuthDto.getStatus());
        adNewsMapper.updateById(wmNews);
        //审核成功保存app端文章数据
        ResponseResult responseResult = saveAppArticle(wmNews);
        if (!responseResult.getCode().equals(200)){
            throw new RuntimeException("文章审核保存app端保存失败");
        }
        //回填articleId
        wmNews.setArticleId((Long) responseResult.getData());
        updateNews(wmNews, (short) 9,"人工审核成功");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 审核内容失败修改文章状态
     * @param wmNews
     * @param Status
     * @param reason
     */
    private void updateNews(WmNews wmNews, short Status, String reason) {
        wmNews.setStatus(Status);
        wmNews.setReason(reason);
        adNewsMapper.updateById(wmNews);
    }
    /**
     * 保存到app端文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto articleDto =new ArticleDto();
        //属性拷贝content
        BeanUtils.copyProperties(wmNews,articleDto);
        //文章布局  0 无图文章   1 单图文章    2 多图文章
        articleDto.setLayout(wmNews.getType());
        //频道查询wmNews中的频道id
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            articleDto.setChannelName(wmChannel.getName());
        }
        //作者id
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        //作者姓名
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            articleDto.setAuthorName(wmUser.getName());
        }
        //在自媒体端存不在文章id 添加在app端文章
        if (wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        //不存在id保存
        //调用文章远程接口
        ResponseResult responseResult = articleClientIp.saveArticle(articleDto);
        return responseResult;

    }
}
